package com.llmcu.tuling.architect.concurrent.countdownlatchsemaphore;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * 用 CountDownLatch 实现“发令枪让运动员一起跑”的功能
 *
 * @author liuling
 * @date 2024/9/16 17:48
 */
public class CountDownLatchReadyRun {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "准备就绪!");
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "开跑...");

                Random random = new Random();
                int seconds = random.nextInt(10);
                try {
                    Thread.sleep(seconds * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(String.format("运动员{%s}耗时{%s}秒跑到终点！", Thread.currentThread().getName(), seconds));
            }).start();
        }
        Thread.sleep(1000);
        System.out.println("开跑！");
        countDownLatch.countDown();

    }
}
